package com.cy.module;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cy.ext.plugin.route.ControllerBind;
import com.cy.model.Point;
import com.cy.model.PointGeneratedLog;
import com.cy.model.User;
import com.cy.utils.RandomCodeGenerator;
import com.cy.utils.TempGetPoint;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@ControllerBind(controllerKey = "/clmp/pointGeneratedLog")
public class PointGeneratedLogController extends WebApiController {

    @Override
    public void index() {
        PointGeneratedLog pointGeneratedLog = getModel(PointGeneratedLog.class);
        int page = getParaToInt("pageIndex");
        int pageSize = getParaToInt("limit");
        String type = getPara("reqType");
        Map<String, String[]> parasMap = getParaMap();
        if (parasMap != null){
            String start_create_time;
            String end_create_time;
            String start_expire_time;
            String end_expire_time;
            if(parasMap.get("start_create_time") != null){
                start_create_time = parasMap.get("start_create_time")[0];
                if (StringUtils.isNotBlank(start_create_time))
                    pointGeneratedLog.put("start_create_time",start_create_time);
            }
            if (parasMap.get("end_create_time") != null) {
                end_create_time = parasMap.get("end_create_time")[0];
                if (StringUtils.isNotBlank(end_create_time))
                    pointGeneratedLog.put("end_create_time",end_create_time);
            }
            if(parasMap.get("start_expire_time") != null) {
                start_expire_time = parasMap.get("start_expire_time")[0];
                if (StringUtils.isNotBlank(start_expire_time))
                    pointGeneratedLog.put("start_expire_time",start_expire_time);
            }
            if (parasMap.get("end_expire_time") != null) {
                end_expire_time = parasMap.get("end_expire_time")[0];
                if (StringUtils.isNotBlank(end_expire_time))
                    pointGeneratedLog.put("end_expire_time",end_expire_time);
            }
        }
        
        Page<PointGeneratedLog> pointRecordPage = PointGeneratedLog.dao.paginate(page, pageSize, PointGeneratedLog.SELECT_ALL, pointGeneratedLog);
        if("1".equals(type)){
        	renderBuiPage(pointRecordPage, 200);
        } else {
        	User user = getLoginUser();
            JSONObject jsonObject = TempGetPoint.selectPoint(String.valueOf(user.getAccount()), "seach_dingquan_list");
            JSONObject json = new JSONObject();
            JSONArray dingquanArry = new JSONArray();
            if("0".equals(jsonObject.getString("ResultCode"))){
            	Object obj = jsonObject.get("list");
            	obj = obj.toString().replace("type_money", "point_num");
            	JSONArray jsonArray = JSON.parseArray(obj.toString());
            	
            	for(Object jsonStr : jsonArray){
            		JSONObject dingquanJson = JSON.parseObject(jsonStr.toString());
            		dingquanJson.put("point_type", 2);
            		dingquanArry.add(dingquanJson);
            	}
            	dingquanArry.add(pointRecordPage.getList());
            	json.put("rows", dingquanArry);
            }
            renderJson(json);
        }
    }

    /**
     * 远程调用
     */
    public void list(){
        forwardAction("/clmp/pointGeneratedLog");
    }

    @Override
    public void show() {
    }

    @Override
    public void update() {
    }

    /**
     * 生成积分
     */
    @Override
    public void save() {
        try {
            Integer amount = getParaToInt("amount");
            Integer pointType = Point.PointType.valueOf(getPara("point_type")).getType();
            Long pointNum = getParaToLong("point_num");
            Date expireTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getPara("expire_time"));

            List<PointGeneratedLog> pointGeneratedLogList = new ArrayList<>(amount);
            Set<String> codes = new HashSet<>(amount);
            for (int i = 0; i < amount; i++){
                PointGeneratedLog pointGeneratedLog = new PointGeneratedLog();
                do {
                    String code = RandomCodeGenerator.randomNumberAndLetter(6);
                    if (!codes.contains(code) && PointGeneratedLog.dao.findByCode(code) == null){
                        codes.add(code);
                        pointGeneratedLog.setCode(code);
                        break;
                    }
                } while (true);
                pointGeneratedLog.setPointType(pointType);
                pointGeneratedLog.setCreateTime(new Date());
                pointGeneratedLog.setExpireTime(expireTime);
                pointGeneratedLog.setPointNum(pointNum);
                pointGeneratedLog.setStatus(0);
                pointGeneratedLogList.add(pointGeneratedLog);
            }
            PointGeneratedLog.dao.saveBatch(pointGeneratedLogList);
            renderSuccess();
        } catch (ParseException e) {
            renderFail();
        }
    }

    @Override
    public void delete() {
        String[] ids = getPara().split("-");
        for (String id : ids) {
            PointGeneratedLog.dao.deleteById(id);
        }
        renderSuccess();
    }

    /**
     * 领取积分
     * @param account 用户名
     * @param password 密码
     * @param code 兑换码
     */
    public void takePoint(){
        User user = isLogined(getPara("account"), getPara("password"));
        if (user == null){
            renderFail("用户名或密码错误");
            return;
        }
        try {
            PointGeneratedLog.dao.takePoint(user, getPara("code"));
            renderSuccess();
        }catch (Exception e){
            renderFail(e.getMessage());
        }
    }

    /**
     * 转赠积分
     * @param account 用户名
     * @param password 密码
     * @param toAccount 转赠给用户
     * @param recordId 记录ID
     */
    public void givePoint(){
        User user = isLogined(getPara("account"), getPara("password"));
        if (user == null){
            renderFail("用户名或密码错误");
            return;
        }
        try {
            PointGeneratedLog.dao.givePoint(user, getParaToLong("recordId"), getPara("toAccount"));
            renderSuccess();
        } catch (Exception e){
            renderFail(e.getMessage());
        }
    }

}
